package com.nwpu.server.learning.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.nwpu.server.common.util.ErrorUtils;
import com.nwpu.server.learning.dao.TaskDao;
import com.nwpu.server.learning.entity.TaskEntity;
import com.nwpu.server.learning.entity.dto.RabbitMqResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;

@Configuration
@Slf4j
public class RabbitMqConfiguration {
    @Resource
    private TaskDao taskDao;

    //队列名称
    private static final String ALGORITHMACKQUEUE = "algorithmAckQueue";
    private static final String ALGORITHMFANOUTEXCHANGEACK = "algorithmFanoutExchangeAck";

    private static final String ALGORITHMEXCHANGE = "algorithmExchange";

    //声明队列
    @Bean("algorithmAckQueue")
    public Queue queue() {
        return QueueBuilder.durable(ALGORITHMACKQUEUE).build();
    }

//    /**
//     * @Description: 定义发送交换器
//     */
//    @Bean(name = "algorithmExchange")
//    public FanoutExchange send() {
//        return new FanoutExchange("ALGORITHMEXCHANGE");
//    }

    /**
     * @Description: 定义接收交换器
     */
    @Bean(name = "algorithmFanoutExchangeAck")
    public FanoutExchange receive() {
        return new FanoutExchange(ALGORITHMFANOUTEXCHANGEACK);
    }

    //绑定队列和交换机
    @Bean
    public Binding itemQueueExchange(@Qualifier("algorithmAckQueue") Queue queue,
                                     @Qualifier("algorithmFanoutExchangeAck") FanoutExchange algorithmFanoutExchangeAck) {
        return BindingBuilder.bind(queue).to(algorithmFanoutExchangeAck);
    }

    /**
     * @Description: 新建队列 algorithmMessages
     */
    @Bean(name = "algorithmMessages")
    public Queue queueMessages() {
        return new Queue("algorithmMessages");
    }


    /**
     * @Description: 交换机与消息队列进行绑定 队列messages绑定交换机with topic.messages
     */
    @Bean
    Binding bindingExchangeMessages(@Qualifier("algorithmMessages") Queue queueMessages, FanoutExchange exchange) {
        return BindingBuilder.bind(queueMessages).to(exchange);
    }

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @RabbitListener(queues = "algorithmAckQueue")
    public void myListener1(Object message) {
        JSONArray body = JSONUtil.parseArray(JSONUtil.parseObj(message).get("body"));

        byte[] bytes = (byte[]) body.toArray(byte.class);

        RabbitMqResponseDTO rabbitMqResponseDTO = null;
        String s = null;
        if (ObjectUtil.isNotEmpty(bytes)) {
            s = new String(bytes);
        } else {
            s = new String();
        }

        try {
            rabbitMqResponseDTO = JSONUtil.toBean(s, RabbitMqResponseDTO.class);
            log.info("对象是:{}", rabbitMqResponseDTO);
        } catch (Exception e) {
            ErrorUtils.errorInfoToString(e);
        }

        // 更新最近字段
        TaskEntity taskEntity = new TaskEntity();
        if (ObjectUtil.isNotNull(rabbitMqResponseDTO) && ObjectUtil.isNotNull(taskDao.selectById(rabbitMqResponseDTO.getId()))) {
            taskEntity.setId(rabbitMqResponseDTO.getId());
            taskEntity.setStatus(rabbitMqResponseDTO.getStatus());
            if (!taskEntity.getUserId().equals("1") && rabbitMqResponseDTO.getStatus() == 2) {
                String text = MailUtil.send(taskEntity.getUserId(), "你的任务已经完成，任务id为 " + taskEntity.getId() + "请到网站上下载查看", "你的任务已经完成，任务id为 " + taskEntity.getId() + "请到网站上下载查看", false, null);
            }
            taskDao.updateById(taskEntity);
        }
    }
}